package offer;


import base.TreeNode;

import java.util.HashMap;
import java.util.Map;

public class BuildTree {

    public Map<Integer, Integer> map = new HashMap<>();

    public static void main(String[] args) {

    }

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || preorder.length == 0 || inorder == null || inorder.length == 0) {
            return null;
        }
        //将中序遍历的下表放在map中
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        TreeNode treeNode = build(0, preorder.length - 1, 0, inorder.length - 1, preorder, inorder);

        return treeNode;
    }

    private TreeNode build(int l1, int r1, int l2, int r2, int[] preorder, int[] inorder) {
        if (l1 > r1 || l2 > r2) {
            return null;
        }
        TreeNode head = new TreeNode(preorder[l1]);
        int m = map.get(preorder[l1]);
        head.left = build(l1 + 1, l1 + (m - l2), l2, m - 1, preorder, inorder);
        head.right = build(l1 + 1 + (m - l2), r1, m + 1, r2, preorder, inorder);
        return head;
    }


}
